const { resolve } = require('path')

const { jgcl } = require(resolve(__dirname, '../../utils/utils'))
const BgImg = require(resolve(__dirname, '../../database/dbModule/bgImg'))

// 新增上传图片
const createUpImg = async (ctx) => {
  try {

    const data = ctx.request.files.file

    /* let fileArr = fs.readdirSync(
      path.join(__dirname, '../../public/upload'),
      { encoding: 'utf8', withFileTypes: true }
    ) */
    const findRes = await BgImg.findOne(
      {
        bgTitle: data.originalFilename.split('.')[0],
        isDel: false
      })
    if (findRes === null) {
      const upRes = BgImg.create({
        bgTitle: data.originalFilename.split('.')[0],
        imgSrc: `http://localhost:3000/${data.newFilename}`,
        isDel: false
      })

      ctx.body = {
        status: {
          code: 200,
          msg: '上传成功!'
        },
        data: null
      }
    } else {
      const upRes = await BgImg.updateOne({
        bgTitle: data.originalFilename.split('.')[0],
      },
        { imgSrc: `http://localhost:3000/${data.newFilename}` }
      )

      ctx.body = {
        status: {
          code: 200,
          msg: '上传成功!'
        },
        data: upRes
      }
    }

  } catch (err) {
    ctx.body = {
      status: {
        code: 2017,
        msg: '上传失败!'
      },
      data: err
    }
  }
}

// 查询所有图片
const findImg = async (ctx) => {
  try {
    const findRes = await BgImg.find({ isDel: false })
    jgcl(ctx, 200, '背景查询成功!', findRes)
  } catch (err) {
    console.log(err)
    jgcl(ctx, 2014, '背景查询失败!', err)
  }
}

// 删除图片
const delImg = async (ctx) => {
  try {
    const { bgTitle } = ctx.request.body
    const delRes = await BgImg.updateOne({ bgTitle, isDel: false }, { isDel: true })
    if (delRes.matchedCount >= 1) {
      jgcl(ctx, 200, '删除成功!')
    } else {
      console.log(delRes)
      jgcl(ctx, 2016, '删除失败!')
    }
  } catch (err) {
    console.log(err)
    jgcl(ctx, 2016, '删除失败!', err)
  }
}


module.exports = {
  createUpImg,
  findImg,
  delImg
}